package com.legolas.web.controller;

import com.legolas.config.upload.Progress;
import com.legolas.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/12/20 0020
 */
@Controller
@RequestMapping("test")
public class IndexController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("upload")
    public String uploadView() {
        return "upload";
    }


    @RequestMapping(value = "uploadfile", method = RequestMethod.POST)
    public String oneFileUpload(@RequestParam("file") CommonsMultipartFile files[], HttpServletRequest request, ModelMap model) {

        logger.info("fileLength->{}", files.length);
        request.getRequestedSessionId();

        List<String> list = new ArrayList<>();

        //上传位置
        String path = Constant.UPLOADFILE;//设定文件保存的目录

        File f = new File(path);
        //不存在的话创建一个目录
        if (!f.exists())
            f.mkdirs();

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            System.out.println("原始文件名：" + fileName);
            String newFileName = UUID.randomUUID() + fileName;
            if (!files[i].isEmpty()) {
                try {
                    files[i].transferTo(new File(path + newFileName));
                    System.out.println("上传文件到:" + path + newFileName);
                    // 保存文件地址
                    list.add(path + newFileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        model.addAttribute("fileList", list);
        return "success";
    }

}
